//
//  MHAskViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/28.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHAskViewModel.h"
#import "MHCircleMember.h"
#import "MHAskItemViewModel.h"

//#import ""
@interface MHAskViewModel ()
@property (nonatomic, readwrite, copy) NSArray *repeaters;
@end

@implementation MHAskViewModel
-(void)initialize
{
    [super initialize];
    self.title = @"提问";
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    
    @weakify(self);
    RAC(self, repeaters) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, repeaters) map:^(NSArray * repeaters) {
        @strongify(self)
        return [self dataSourceWithRepeaters:repeaters];
    }];
    
    self.requstAskCountCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        return  [[self.services.client getMyQuestionCountWithCircleId:self.info.autoId] doNext:^(MHHTTPResponse *response) {
            self.askCount = [[[response parsedResult] objectForKey:@"countQuestion"] intValue];
            self.dataSource = [self dataSourceWithRepeaters:self.repeaters];
        }];
    }];
}

-(instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params
{
    if (self = [super initWithServices:services params:params]) {
        self.info = params[MHViewModelUtilKey];
    }
    return self;
}


- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapRepeaters)(NSArray *) = ^(NSArray *repeaters) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            repeaters = @[(self.repeaters ?: @[]).rac_sequence, repeaters.rac_sequence].rac_sequence.flatten.array;
        }
        return repeaters;
    };

    return [[self.services.client getCircleQuestionerListWithCircleId:self.info.autoId] map:mapRepeaters];
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithRepeaters:(NSArray *)repeaters {
    MHCircleMember *all = [[MHCircleMember alloc] init];
    all.nickName = @"所有人";
//    all.autoId = -1;
    all.qaInfo = @"发起提问后，圈内所有人能收到你的提问";
    all.askCount = self.askCount;
    MHAskItemViewModel *allViewModel =  [[MHAskItemViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:all}];
    allViewModel.isAll = YES;
    allViewModel.info = self.info;
    if (MHObjectIsNil(repeaters) || repeaters.count == 0) return @[allViewModel];
    NSMutableArray *viewModels = [[repeaters.rac_sequence map:^(MHCircleMember *repeater) {
        MHAskItemViewModel *viewModel = [[MHAskItemViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:repeater}];
        viewModel.info = self.info;
        return viewModel;
    }].array mutableCopy];
    [viewModels appendObject:allViewModel];
    return viewModels ?: @[] ;
}

@end
